package service

import (
	"gorm.io/gorm"
	"myApp/model"
)

type GetServiceRequest struct {
	CustId    string `json:"custId"`
	Mobile    string `json:"mobile"`
	SendLimit int64  `json:"sendLimit" validate:"gte:0"`
	PushRatio uint8  `json:"pushRatio" validate:"gte:0,lte:100"`
	RiskRatio uint8  `json:"riskRatio" validate:"gte:0,lte:100"`
}

type GetServiceResponse struct {
	//Id        int64  `json:"id"`
	//CustId    string `json:"custId"`
	//Mobile    string `json:"mobile"`
	//RealName  string `json:"realName"`
	//Province  string `json:"province"`
	//City      string `json:"city"`
	//Address   string `json:"address"`
	//LoginIp   string `json:"loginIp"`
	//LoginTime time.Time `json:"loginTime"`
	//Enable    uint64 `json:"enable"`
	//VipLevel  uint64 `json:"vipLevel"`
	CustInfo  *model.CustInfo
	PushRatio uint8  `json:"pushRatio"`
	SendNum   uint64 `json:"sendNum"`
	RiskRatio uint64 `json:"riskRatio"`
}

type ExportServiceRequest struct {
	SendLimit      uint64 `json:"sendLimit"`
	PushRatio      uint8  `json:"pushRatio"`
	RiskRatio      uint8  `json:"riskRatio"`
	ProvFilterType string `json:"provFilterType"`
	Province       string `json:"province"`
}

type ExportServiceResponse struct {
	Url string `json:"url"`
}

//func GetService(request *GetServiceRequest) (*GetServiceResponse, error) {
//	response := &GetServiceResponse{}
//	var err error
//	// TODO 还是得做成事务或者连表查询 加索引
//	// 如果没传custid 从mobile获取
//	if len(request.CustId) == 0 {
//		request.CustId, err = model.GetCustIdFromMobile(request.Mobile)
//		if err != nil {
//			return response, err
//		}
//	}
//	// 查询具体用户营销次数
//	times, err := model.GetSendCnt(request.CustId)
//	if err != nil {
//		return response, err
//	}
//	var pushRatio uint8
//	var riskRatio uint8
//	// 输出满足条件的信息
//	if (request.SendLimit == 0 || times < request.SendLimit) &&
//		(pushRatio == 0 || request.PushRatio == 0 || pushRatio >= request.PushRatio) &&
//		(riskRatio == 0 || request.RiskRatio == 0 || riskRatio <= request.RiskRatio) {
//		if err = model.GetUserInfo(response.CustInfo); err != nil {
//			return response, nil
//		}
//	} else {
//		return nil, nil
//	}
//	// 增加查询次数
//	if err = model.AddRecord(request.CustId); err != nil {
//		return response, err
//	}
//	// 返回信息
//	return response, nil
//}

func GetService(request *GetServiceRequest) (*GetServiceResponse, error) {
	response := &GetServiceResponse{}
	response.CustInfo.CustId = request.CustId
	response.CustInfo.Mobile = request.Mobile
	err := model.DB.Transaction(func(tx *gorm.DB) error {
		var err error
		// 从mobile 获取 custid
		if len(request.CustId) == 0 {
			err = model.GetCustIdFromMobile(tx, response.CustInfo)
			if err != nil {
				return err
			}
		}
		// 查询具体用户营销次数
		_, err = model.GetSendCnt(tx, request.CustId)
		if err != nil {
			return err
		}
		// 判断是否满足条件

		// 增加记录
		err = model.AddRecord(response.CustInfo.CustId)
		if err != nil {
			return err
		}
		// redis 同步

		return nil
	})
	if err != nil {
		return nil, err
	}
	return response, nil
}
